#include "SearchEngineServer.hpp"
#include "Configuration.hpp"
#include "Debug.hpp"

#include <iostream>

namespace se {

SearchEngineServer::SearchEngineServer()
: _threadPool(CONFIGURATION("ThreadCountOfThreadPool", int32_t), CONFIGURATION("TaskQueueCapacity", int32_t))
, _tcpServer(CONFIGURATION("IP", std::string).c_str(), CONFIGURATION("Port", unsigned short))
{ }

void SearchEngineServer::start() {
    this->_threadPool.start();

    this->_tcpServer.OnTcpConnected += [](std::shared_ptr<TcpConnection> tcpConnection) { 
        std::cout << tcpConnection->toString() << " connect success." << std::endl;
    };

    this->_tcpServer.OnTcpMessageReceived += [this](std::shared_ptr<TcpConnection> tcpConnection) {
        std::string message = tcpConnection->receive();
        if (message.empty()) return;
        this->_threadPool.addTask([message, tcpConnection]() {
            DEBUG_PRINT("thread %ld is running.\n", ::pthread_self());
            DEBUG_PRINT("%s", message.c_str());
            KeyRecommender keyRecommender(message);
            tcpConnection->send(keyRecommender.queryResult()->dump());
        });
    };

    this->_tcpServer.OnTcpClosed += [](std::shared_ptr<TcpConnection> tcpConnection) {
        std::cout << tcpConnection->toString() << " disconnect." << std::endl;
    };
    
    this->_tcpServer.start();
}

}  // namespace se